/* eslint-disable @typescript-eslint/no-var-requires */
import { Injectable, NotFoundException, StreamableFile } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { MediaEntiry } from '../entities';
import { Repository } from 'typeorm';
import { MultipartFile } from '@fastify/multipart';
import { generateFileName, uploadFileToCos } from '../helper';
import { rootPath } from '../config';
import { lookup } from 'mime-types';
import { extname, join } from 'path';
import { createReadStream, existsSync } from 'fs-extra';
import { FastifyReply } from 'fastify';
@Injectable()
export class MediaService {
  constructor(
    @InjectRepository(MediaEntiry)
    private readonly mediaRepository: Repository<MediaEntiry>,
  ) {}
  async upload(file: MultipartFile, dir: string) {
    try {
      const fileName = generateFileName(file.filename);
      const location = await uploadFileToCos(file, fileName, dir);
      const media = this.mediaRepository.create();
      media.filename = fileName;
      media.file = location as string;
      media.ext = extname(fileName);
      await media.save();
      return media;
    } catch (error) {
      console.log(error.message);
    }
  }
  async detail(id: string) {
    return await this.mediaRepository.findOneByOrFail({
      id,
    });
  }
  async loadImage(id: string, res: FastifyReply) {
    const media = await this.detail(id);
    const filePath = join(rootPath, media.file);
    if (!existsSync(filePath)) {
      throw new NotFoundException('file not exists!');
    }
    const stream = await createReadStream(filePath);
    res.type(lookup(filePath) as string);
    return new StreamableFile(stream);
  }
}
